package railRoad.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminFilter implements Filter {
	private static final List<String> secureUrls = new ArrayList<String>();

	public void init(FilterConfig filterConfig) throws ServletException {
		secureUrls.add("/pages/route_remove.do");
		secureUrls.add("/pages/station_create.do");
		secureUrls.add("/pages/station_edit.do");
		secureUrls.add("/pages/station_upgrade.do");
		secureUrls.add("/pages/route_create.do");
		secureUrls.add("/pages/route_edit.do");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest req = (HttpServletRequest) request;
		final HttpServletResponse resp = (HttpServletResponse) response;

		if (!Boolean.TRUE.equals(req.getSession(true).getAttribute("admin"))
				&& secureUrls.contains(req.getRequestURI())) {
			req.getSession().removeAttribute("auth");
			req.getSession().setAttribute("page", req.getRequestURI());
			req.getSession().setAttribute("notAdmin", Boolean.TRUE);
			resp.sendRedirect("/pages/login.jsp");
			return;
		}
		
		chain.doFilter(request, response);
	}// doFilter

	public void destroy() {
	}

}
